package utils

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"golang.org/x/net/context"
	"io"
	"os"
)

func DockerPull(name string) {
	imageName := fmt.Sprintf("%s/%s:latest", imgHost, name)
	fmt.Println(imageName)
	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}

	authConfig := types.AuthConfig{
		Username:      username,
		Password:      password,
		ServerAddress: host,
	}
	encodedJSON, err := json.Marshal(authConfig)
	if err != nil {
		panic(err)
	}
	authStr := base64.URLEncoding.EncodeToString(encodedJSON)

	out, err := cli.ImagePull(ctx, imageName, types.ImagePullOptions{RegistryAuth: authStr})
	if err != nil {
		panic(err)
	}

	defer out.Close()
	io.Copy(os.Stdout, out)
}

func DockerPush(name string, version string) {
	sourImageName := fmt.Sprintf("%s/%s:latest", imgHost, name)
	destImageName := fmt.Sprintf("%s/%s:%s", imgHost, name, version)
	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}

	authConfig := types.AuthConfig{
		Username:      username,
		Password:      password,
		ServerAddress: host,
	}
	encodedJSON, err := json.Marshal(authConfig)
	if err != nil {
		panic(err)
	}
	authStr := base64.URLEncoding.EncodeToString(encodedJSON)

	err = cli.ImageTag(ctx, sourImageName, destImageName)
	if err != nil {
		panic(err)
	}

	out, err := cli.ImagePush(ctx, destImageName, types.ImagePushOptions{RegistryAuth: authStr})
	if err != nil {
		panic(err)
	}

	defer out.Close()
	io.Copy(os.Stdout, out)
}
